import CachedVariableManager from '../../../_cachedVariableManager'
abstract class Tokens<T> extends CachedVariableManager<T> {
  /**
   * 刷新tokens
   * @param requestToken
   * @param extractExpireIn
   * @returns
   */
  public async tryRefreshToken(): Promise<boolean> {
    let oldTokens: T | null = this.getValue()
    if (oldTokens != null) {
      // 之前的token信息还存在，准备去刷新
      try {
        const newTokens = await this.refreshToken(oldTokens)
        this.setValue(newTokens, this.extractExpireIn(newTokens))
        return true
      } catch {
        // 无法刷新，判定token无效，返回上面代码去登录
        // 当登录页面会检查是否存在用户信息时自动转首页，此时就需要清理掉
        this.clearValue()
        oldTokens = this.value = null
      }
    }
    // 准备登录操作
    return await this.login()
      .then((result) => result)
      .catch(() => false)
  }
  /**
   * 判断是否存在登录信息
   */
  public hasLoginInfo(): boolean {
    return this.getValue() != null
  }

  public abstract getAccessToken(): string | null
  public abstract refreshToken(oldToken: T): Promise<T>
  public abstract extractExpireIn(newToken: T): number
  public abstract login(): Promise<boolean>
}
export default Tokens
